package ldh.im.fxgui.demo;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import ldh.im.fxbase.util.ThreadPoolUtil;
import ldh.im.fxgui.util.ImageUtil;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class GifDemo extends Application {

    private Image image; // 预先加载所有帧
    private ImageView imageView = new ImageView();
    private Iterator<ImageReader> readers;
    private int numImages = 0;
    private ImageReader reader;
    private int delayTime = 200;

    @Override
    public void start(Stage primaryStage) throws Exception {
//        Image gifImage = ImageUtil.getCacheImage("E:\\logs\\1744032897017.gif");

        File file = new File("E:\\logs\\1744032897017.gif");
        ImageInputStream iis = ImageIO.createImageInputStream(file);
        Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
        if (readers.hasNext()) {
            reader = readers.next();
            reader.setInput(iis);

            numImages = reader.getNumImages(true); // 获取GIF中的帧数
            System.out.println("numImages: " + numImages);
            IIOMetadata metadata = reader.getStreamMetadata();
            if (metadata != null) {
                String[] metadataNames = metadata.getMetadataFormatNames();
                for (String name : metadataNames) {
                    if (name.equalsIgnoreCase("javax_imageio_gif_image_1.0")) {
                        Node node = metadata.getAsTree(name);
                        NodeList graphicControlExtensions = node.getChildNodes();
                        for (int i = 0; i < graphicControlExtensions.getLength(); i++) {
                            Node graphicControlExtension = graphicControlExtensions.item(i);
                            if ("GraphicControlExtension".equals(graphicControlExtension.getNodeName())) {
                                NamedNodeMap attributes = graphicControlExtension.getAttributes();
                                Node delayNode = attributes.getNamedItem("delayTime"); // In milliseconds
                                if (delayNode != null) {
                                    delayTime = Integer.parseInt(delayNode.getNodeValue());
                                    System.out.println("delayTime:" + delayTime);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        StackPane stackPane = new StackPane(imageView);
        Scene scene = new Scene(stackPane, 600, 800);
        primaryStage.setScene(scene);
        primaryStage.show();

        AtomicInteger index = new AtomicInteger(0);
        ThreadPoolUtil.scheduleAtFixedRate(()->{
            try {
                int idx = index.getAndIncrement();
                if (idx >= numImages) {
                    idx = 0;
                    index.set(idx);
                }
                BufferedImage bufferedImage = reader.read(idx);
                imageView.setImage(SwingFXUtils.toFXImage(bufferedImage, null));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }, 100, delayTime, TimeUnit.MILLISECONDS);
    }
}
